package cn.edu.sgu.www.mhxysy.util;

import cn.edu.sgu.www.mhxysy.dto.system.MessageDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Component
public class EmailSender {

    private final JavaMailSender javaMailSender;
    private final MailProperties mailProperties;

    @Autowired
    public EmailSender(JavaMailSender javaMailSender, MailProperties mailProperties) {
        this.javaMailSender = javaMailSender;
        this.mailProperties = mailProperties;
    }

    /**
     * 发送邮件，支持批量发送
     * @param messageDTO 邮件的信息
     */
    public void sendMessage(MessageDTO messageDTO) throws MessagingException {
        List<String> users = messageDTO.getUsers();

        if (CollectionUtils.isNotEmpty(users)) {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);

            helper.setFrom(mailProperties.getUsername());

            for (String to : users) {
                helper.setTo(to);
                helper.setText(messageDTO.getContent());

                javaMailSender.send(message);
            }
        }
    }

}